<template>
  <el-dialog
      v-model="dialogVisible"
      title="添加报备字段配置"
      width="800px"
      :close-on-click-modal="false"
      :destroy-on-close="true"
  >
    <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        label-position="top"
    >
      <!-- 学期选择 -->
      <el-form-item label="学期" prop="term">
        <el-select
            v-model="formData.term"
            placeholder="请选择学期"
            class="full-width"
            filterable
        >
          <el-option
              v-for="term in terms"
              :key="term"
              :label="term"
              :value="term"
          />
        </el-select>
      </el-form-item>

      <!-- 报备名称 -->
      <el-form-item label="报备名称" prop="report_name">
        <el-input
            v-model="formData.report_name"
            placeholder="请输入报备名称"
            clearable
        />
      </el-form-item>

      <!-- 报备说明 -->
      <el-form-item label="报备说明" prop="report_description">
        <el-input
            v-model="formData.report_description"
            type="textarea"
            :rows="3"
            placeholder="请输入报备说明"
            clearable
        />
      </el-form-item>

      <!-- 报备字段配置 -->
      <el-form-item label="报备字段配置" prop="report_fields">
        <!-- 模式切换 -->
        <el-radio-group v-model="fieldConfigMode" size="small" style="margin-bottom: 15px;">
          <el-radio-button label="manual">手动配置</el-radio-button>
          <el-radio-button label="json">JSON输入</el-radio-button>
        </el-radio-group>

        <!-- 手动配置面板 -->
        <div v-show="fieldConfigMode === 'manual'" class="field-config-container">
          <div class="field-list">
            <div
                v-for="(field, index) in formData.report_fields"
                :key="index"
                class="field-item"
            >
              <div class="field-header">
                <span class="field-title">字段 {{ index + 1 }}</span>
                <el-button
                    type="danger"
                    size="small"
                    icon="Delete"
                    circle
                    @click="removeField(index)"
                />
              </div>

              <div class="field-body">
                <div class="field-row">
                  <div class="field-input">
                    <label>字段键名：</label>
                    <el-input
                        v-model="field.key"
                        placeholder="如：competition_level"
                        size="small"
                    />
                  </div>

                  <div class="field-input">
                    <label>字段标签：</label>
                    <el-input
                        v-model="field.label"
                        placeholder="如：竞赛级别"
                        size="small"
                    />
                  </div>
                </div>

                <div class="options-section">
                  <div class="options-header">
                    <span>选项列表</span>
                    <el-button
                        type="primary"
                        size="small"
                        icon="Plus"
                        @click="addOption(index)"
                    >
                      添加选项
                    </el-button>
                  </div>

                  <div class="options-list">
                    <div
                        v-for="(option, optIndex) in field.choice"
                        :key="optIndex"
                        class="option-item"
                    >
                      <el-input
                          v-model="field.choice[optIndex]"
                          placeholder="输入选项内容"
                          size="small"
                      />
                      <el-button
                          type="danger"
                          size="small"
                          icon="Delete"
                          circle
                          @click="removeOption(index, optIndex)"
                      />
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <el-button
              type="primary"
              plain
              icon="Plus"
              class="add-field-btn"
              @click="addNewField"
          >
            添加新字段
          </el-button>
        </div>

        <!-- JSON输入面板 -->
        <el-input
            v-show="fieldConfigMode === 'json'"
            v-model="jsonFieldInput"
            type="textarea"
            :rows="8"
            placeholder="请输入符合要求的JSON格式字段配置（示例见底部提示）"
            style="width: 100%; margin-top: 10px;"
        />

        <!-- 使用帮助 -->
        <div class="config-help">
          <p>JSON格式要求：</p>
          <pre>
[
  {
    "key": "字段键名",
    "label": "字段标签",
            //如不要选项可以设置为[]
    "choice": ["选项1", "选项2"]
  }
]
          </pre>
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" :loading="submitLoading" @click="submitForm" >
        {{ submitLoading  ? '正在添加' : '确认' }}
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import {ref, reactive, watch, computed} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import {jsonApi} from "@/global.js";

// 接收父组件传递的属性
const props = defineProps({
  tableType: {
    type: String,
    required: true
  },
  isAdmin: {
    type: Boolean,
    default: false
  }
});

// 定义事件
const emit = defineEmits(['refresh-table']);

// 学期选项
const terms = ref([
  '2023-2024学年秋季学期',
  '2023-2024学年春季学期',
  '2024-2025学年秋季学期',
  '2024-2025学年春季学期',
  '2025-2026学年秋季学期',
  '2025-2026学年春季学期',
  '2026-2027学年秋季学期',
  '2026-2027学年春季学期',
  '2027-2028学年秋季学期',
  '2027-2028学年春季学期',
  '2028-2029学年秋季学期',
  '2028-2029学年春季学期',
]);

// 对话框显示状态
const dialogVisible = ref(false);

//  表单提交状态
const submitLoading = ref(false);

// 表单引用
const formRef = ref(null);

// 字段配置模式：manual | json
const fieldConfigMode = ref('manual');

// JSON输入内容
const jsonFieldInput = ref('');

// 表单数据
const formData = reactive({
  term: '',
  report_name: '',
  report_fields: [
    {
      key: '',
      label: '',
      choice: []
    }
  ],
  report_description: ''
});

// 表单验证规则
const formRules = reactive({
  term: [
    {required: true, message: '请选择学期', trigger: 'blur'}
  ],
  report_name: [
    {required: true, message: '请输入报备名称', trigger: 'blur'},
    {min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur'}
  ],
  report_fields: [
    {
      validator: (rule, value, callback) => {
        if (!value || value.length === 0) {
          callback(new Error('至少需要配置一个字段'));
          return;
        }

        for (const field of value) {
          if (!field.key.trim()) {
            callback(new Error('所有字段键名不能为空'));
            return;
          }
          if (!field.label.trim()) {
            callback(new Error('所有字段标签不能为空'));
            return;
          }
          if (field.hasOwnProperty('choose') && field.choose.length > 0) {
            if (field.choose.some(opt => !opt || !opt.trim())) {
              callback(new Error('所有选项内容不能为空'));
              return;
            }

            const uniqueOptions = new Set(field.choose.map(opt => opt.trim()));
            if (uniqueOptions.size !== field.choose.length) {
              callback(new Error('所有选项内容必须唯一，不能重复'));
              return;
            }
          }

        }


        callback();
      },
      trigger: 'blur'
    }
  ]
});

// 添加新字段
const addNewField = () => {
  formData.report_fields.push({
    key: '',
    label: '',
    choice: []
  });
};

// 移除字段
const removeField = (index) => {
  if (formData.report_fields.length > 1) {
    formData.report_fields.splice(index, 1);
  } else {
    ElMessage.warning('至少需要保留一个字段');
  }
};

// 添加选项
const addOption = (fieldIndex) => {
  formData.report_fields[fieldIndex].choice.push('');
};

// 移除选项
const removeOption = (fieldIndex, optionIndex) => {
  if (formData.report_fields[fieldIndex].choice.length > 0) {
    formData.report_fields[fieldIndex].choice.splice(optionIndex, 1);
  } else {
    ElMessage.warning('至少需要保留一个选项');
  }
};

// 监听字段配置模式变化
watch(fieldConfigMode, (newMode, oldMode) => {
  if (newMode === 'json' && oldMode === 'manual') {
    // 手动切换到JSON
    try {
      jsonFieldInput.value = JSON.stringify(formData.report_fields, null, 2);
    } catch (error) {
      ElMessage.error('字段数据转换失败');
      fieldConfigMode.value = 'manual';
    }
  } else if (newMode === 'manual' && oldMode === 'json') {
    // JSON切换到手动
    if (jsonFieldInput.value.trim()) {
      try {
        const parsed = JSON.parse(jsonFieldInput.value);
        if (Array.isArray(parsed)) {
          formData.report_fields = parsed;
        } else {
          throw new Error('JSON格式不正确，应为数组');
        }
      } catch (error) {
        ElMessageBox.confirm(
            `JSON解析失败：${error.message}，是否返回手动配置模式？`,
            '错误',
            {type: 'error'}
        ).then(() => {
          fieldConfigMode.value = 'manual';
        }).catch(() => {
          fieldConfigMode.value = 'json';
        });
      }
    }
  }
});

// 提交表单
const submitForm = async () => {
  try {
    submitLoading.value = true;
    // 处理JSON模式
    if (fieldConfigMode.value === 'json') {
      if (!jsonFieldInput.value.trim()) {
        ElMessage.error('请输入JSON配置');
        return;
      }
      try {
        const parsed = JSON.parse(jsonFieldInput.value);
        formData.report_fields = parsed;
      } catch (error) {
        ElMessage.error(`JSON格式错误：${error.message}`);
        return;
      }
    }

    // 验证表单
    await formRef.value.validate();

    // 准备提交数据
    const submitData = {
      ...formData,
    };

    // API请求
    const response = await jsonApi("/newreport/field/create/", JSON.stringify(submitData));
    // 判断请求为200
    if (response.ok) {
      // 提示添加成功
      ElMessage.success('添加成功');
      // 关闭状态
      submitLoading.value = false;
      // 关闭对话框
      dialogVisible.value = false;
    }


    // 通知父组件刷新表格
    emit('refresh-table');
  } catch (error) {
    submitLoading.value = false;
    console.error('表单验证失败:', error);
    if (error instanceof Error) {
      ElMessage.error(`添加失败: ${error.message}`);

    }
  }
};

// 打开对话框的方法
const open = () => {
  // 重置表单数据
  Object.assign(formData, {
    term: '',
    report_name: '',
    report_fields: [
      {
        key: '',
        label: '',
        choice: []
      }
    ],
    report_description: ''
  });
  fieldConfigMode.value = 'manual';
  jsonFieldInput.value = '';

  // 打开对话框
  dialogVisible.value = true;
};

// 暴露open方法给父组件
defineExpose({open});
</script>

<style scoped>
.full-width {
  width: 100%;
}

.field-config-container {
  border: 1px solid #ebeef5;
  border-radius: 8px;
  padding: 15px;
  background-color: #f8fafc;
}

.field-list {
  margin-bottom: 15px;
}

.field-item {
  background: white;
  border-radius: 6px;
  padding: 15px;
  margin-bottom: 15px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  border: 1px solid #ebeef5;
}

.field-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.field-title {
  font-weight: bold;
  color: #409eff;
}

.field-body {
  padding: 0 10px;
}

.field-row {
  display: flex;
  gap: 15px;
  margin-bottom: 15px;
}

.field-input {
  flex: 1;
}

.field-input label {
  display: block;
  margin-bottom: 5px;
  font-size: 13px;
  color: #606266;
}

.options-section {
  background: #f5f7fa;
  border-radius: 6px;
  padding: 10px;
}

.options-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  font-weight: bold;
  color: #67c23a;
}

.options-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.option-item {
  display: flex;
  gap: 10px;
  align-items: center;
}

.option-item .el-input {
  flex: 1;
}

.add-field-btn {
  width: 100%;
  margin-top: 10px;
}

.config-help {
  margin-top: 10px;
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 4px;
  font-size: 12px;
  color: #666;
}

.config-help pre {
  margin: 0;
  padding: 0;
  background-color: transparent;
  border: none;
  font-family: monospace;
  line-height: 1.5;
}
</style>